//===========================================================================================================================
// Cuberry - http://www.cuberry.net
// Copyright (c) 2012
// by Peacequare® - Amir Moussa
//===========================================================================================================================
// This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License 
// as published by the Free Software Foundation, either version 3 of the License, or any later version.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software.
//
// This program is distributed in the hope that it will be useful.
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE.
//
// See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program.  If not, see <http://www.gnu.org/licenses/>.
//===========================================================================================================================

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using Microsoft.Practices.Prism.Commands;
using P2.Cuberry.Framework.Helper;


namespace P2.Cuberry.Modules.Clinicom.CCPatientVisit
{
    public class CCPatientVisitsDetailsPresentationModel : INotifyPropertyChanged, IDisposable, IDataErrorInfo
    {

        public CCPatientVisitsDetailsPresentationModel(ICCPatientVisitsDetailsView view, BusinessEntities.CCPatientVisit model, Services.ICCPatientVisitService service)
        {
            try
            {
                View = view;
                this.Model = model;
                this.Service = service;

                //DDL++
                this.CCPatients = BusinessEntities.CCPatient.GetList;
                this.CCBeds = BusinessEntities.CCBed.GetList;
                this.CCVisitCategorys = BusinessEntities.CCVisitCategory.GetList;
                this.CROrganisations = BusinessEntities.CROrganisation.GetList;

                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "CCPatientVisitsDetailsView");
                MessageStack = new P2MessageStack();
                View.Model = this;

                this.CCPatientVisitSaveCommand = new DelegateCommand<object>(OnCCPatientVisitSaveExecute, OnCCPatientVisitSaveCanExecute);
                this.CCPatientVisitCloseCommand = new DelegateCommand<object>(OnCCPatientVisitCloseExecute, OnCCPatientVisitCloseCanExecute);

                this.InfoCommand = new DelegateCommand<object>(OnInfoExecute, OnInfoCanExecute);
                this.HistoryCommand = new DelegateCommand<object>(OnHistoryExecute, OnHistoryCanExecute);


                this.RefreshView();
            }
            catch (Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        #region Members

        public int PatientVisitID
        {
            get { return Model.VisitID; }
        }

        //Add++

        public DateTime? OpeningTime //check if nullable? 
        {
            get { return Model.OpeningTime; }
            set
            {
                if (value != Model.OpeningTime)
                {
                    Model.OpeningTime = value;
                    OnPropertyChanged("OpeningTime");
                }
            }
        }

        public DateTime? ClosingTime //check if nullable? 
        {
            get { return Model.ClosingTime; }
            set
            {
                if (value != Model.ClosingTime)
                {
                    Model.ClosingTime = value;
                    OnPropertyChanged("ClosingTime");
                }
            }
        }

        public string LeavingStatus //check if nullable? 
        {
            get { return Model.LeavingStatus; }
            set
            {
                if (value != Model.LeavingStatus)
                {
                    Model.LeavingStatus = value;
                    OnPropertyChanged("LeavingStatus");
                }
            }
        }

        public string ClosedBy //check if nullable? 
        {
            get { return Model.ClosedBy; }
            set
            {
                if (value != Model.ClosedBy)
                {
                    Model.ClosedBy = value;
                    OnPropertyChanged("ClosedBy");
                }
            }
        }

        public string Diagnosis //check if nullable? 
        {
            get { return Model.Diagnosis; }
            set
            {
                if (value != Model.Diagnosis)
                {
                    Model.Diagnosis = value;
                    OnPropertyChanged("Diagnosis");
                }
            }
        }

        public string TherapyDuration //check if nullable? 
        {
            get { return Model.TherapyDuration; }
            set
            {
                if (value != Model.TherapyDuration)
                {
                    Model.TherapyDuration = value;
                    OnPropertyChanged("TherapyDuration");
                }
            }
        }

        public string Note //check if nullable? 
        {
            get { return Model.Note; }
            set
            {
                if (value != Model.Note)
                {
                    Model.Note = value;
                    OnPropertyChanged("Note");
                }
            }
        }



        //DDL++

        public int PatientID //check if nullable? 
        {
            get { return Model.PatientID; }
            set
            {
                if (value != Model.PatientID)
                {
                    if (value == -1)
                        Model.PatientID = -1;
                    else
                        Model.PatientID = value;
                    OnPropertyChanged("PatientID");
                }
            }
        }

        public int BedID //check if nullable? 
        {
            get { return Model.BedID.GetValueOrDefault(-1); }
            set
            {
                if (value != Model.BedID)
                {
                    if (value == -1)
                        Model.BedID = null;
                    else
                        Model.BedID = value;
                    OnPropertyChanged("BedID");
                }
            }
        }

        public int VisitCategoryID //check if nullable? 
        {
            get { return Model.VisitCategoryID.GetValueOrDefault(-1); }
            set
            {
                if (value != Model.VisitCategoryID)
                {
                    if (value == -1)
                        Model.VisitCategoryID = null;
                    else
                        Model.VisitCategoryID = value;
                    OnPropertyChanged("VisitCategoryID");
                }
            }
        }

        public int Contractor //check if nullable? 
        {
            get { return Model.Contractor.GetValueOrDefault(-1); }
            set
            {
                if (value != Model.Contractor)
                {
                    if (value == -1)
                        Model.Contractor = null;
                    else
                        Model.Contractor = value;
                    OnPropertyChanged("Contractor");
                }
            }
        }



        #endregion


        #region Computed Members

        public string StatusName
        {
            get { return Model.CurrentStatus.StatusNameCur; }
        }

        public bool ModelIsModified
        {
            get
            {
                return Model.Modified;
            }
        }

        public bool IsReadOnly
        {
            get
            {
                P2.Cuberry.Framework.Security.User.ControlRight controlRight;
                if (ControlRights.TryGetValue("CCPatientVisitSaveBtn", out controlRight))
                    return !controlRight.IsActive;
                else
                    return true;
            }
        }

        public bool IsEditable
        {
            get
            {
                return !IsReadOnly;
            }
        }

        #endregion


        #region Reference Tables

        //DDL++
        public List<BusinessEntities.CCPatient> CCPatients { get; set; }
        public List<BusinessEntities.CCBed> CCBeds { get; set; }
        public List<BusinessEntities.CCVisitCategory> CCVisitCategorys { get; set; }
        public List<BusinessEntities.CROrganisation> CROrganisations { get; set; }




        //public List<P2.Cuberry.Framework.Helper.Workflows.WorkflowStatus> WorkflowStatusses { get; set; }

        #endregion


        #region Commands

        public DelegateCommand<object> CCPatientVisitSaveCommand { get; set; }
        public DelegateCommand<object> CCPatientVisitCloseCommand { get; set; }
        public DelegateCommand<object> CCPatientVisitPrintCommand { get; set; }

        public DelegateCommand<object> InfoCommand { get; set; }
        public DelegateCommand<object> HistoryCommand { get; set; }

        void OnCCPatientVisitSaveExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            this.Save();
            this.RefreshView();
            return;
        }

        bool OnCCPatientVisitSaveCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("CCPatientVisitSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnCCPatientVisitCloseExecute(object sourceAccount)
        {
            View.UpdateFocusedControl();
            if (this.Save())
            {
                View.Close();
            }
        }

        bool OnCCPatientVisitCloseCanExecute(object sourceAccount)
        {
            P2.Cuberry.Framework.Security.User.ControlRight controlRight;
            if (ControlRights.TryGetValue("CCPatientVisitSaveBtn", out controlRight))
                return controlRight.IsActive;
            else
                return false;
        }

        void OnInfoExecute(object sourceItem)
        {
            Model.GetObjectInfo();
            return;
        }

        bool OnHistoryCanExecute(object sourceItem)
        {
            return true;
        }


        void OnHistoryExecute(object sourceItem)
        {
            Model.GetObjectHistory("CCPatientVisit", "CCPatientVisit", this.Model.VisitID);
            return;
        }

        bool OnInfoCanExecute(object sourceItem)
        {
            return true;
        }

        //Add++
        public void RefreshView()
        {
            try
            {
                ControlRights = Model.GetControls(Properties.Settings.Default.ModuleName, "CCPatientVisitsDetailsView");
                OnPropertyChanged("VisitID");

                OnPropertyChanged("OpeningTime");
                OnPropertyChanged("ClosingTime");
                OnPropertyChanged("LeavingStatus");
                OnPropertyChanged("ClosedBy");
                OnPropertyChanged("Diagnosis");
                OnPropertyChanged("TherapyDuration");
                OnPropertyChanged("Note");



                //Standard Fields
                OnPropertyChanged("StatusName");

                this.CCPatientVisitCloseCommand.RaiseCanExecuteChanged();
                this.CCPatientVisitSaveCommand.RaiseCanExecuteChanged();
            }
            catch (System.Exception ex) //AM:TC
            {
                P2ExceptionHandler.LogException(ex, string.Format("{0}.{1}", this.GetType().Name, System.Reflection.MethodInfo.GetCurrentMethod().Name));
            }
        }


        public bool Save()
        {
            bool isNewItem = (this.PatientVisitID <= 0);
            MessageStack.Clear();
            Model.InsertAndUpdate(MessageStack, true);

            if (MessageStack.StatusMessage.MessageStatus != P2ValidationStatus.red && !Model.Modified)
            {
                return true;
            }
            else
                return false;

        }


        //Find++
        public ObservableCollection<BusinessEntities.CCPatientVisit> GetPatientVisits()
        {
            ObservableCollection<BusinessEntities.CCPatientVisit> _myItemDT = Service.RetrievePatientVisits();
            var ordered = _myItemDT; //.OrderBy(f => f.FirstNameEn); --->>> If they have to be sorted!
            ObservableCollection<BusinessEntities.CCPatientVisit> result = new ObservableCollection<BusinessEntities.CCPatientVisit>();

            foreach (var xItem in ordered)
            {
                result.Add(xItem);
            }
            return result;
        }

        #endregion


        #region Model & View Components

        public ICCPatientVisitsDetailsView View { get; set; }

        public Services.ICCPatientVisitService Service;
        public BusinessEntities.CCPatientVisit Model { get; set; }
        public Dictionary<string, P2.Cuberry.Framework.Security.User.ControlRight> ControlRights;

        protected P2MessageStack myMessageStack = new P2MessageStack();
        public P2MessageStack MessageStack
        {
            get
            {
                return myMessageStack;
            }
            set
            {
                myMessageStack = value;
                OnPropertyChanged("MessageStack");
            }
        }

        #endregion


        #region Property Changed

        public event PropertyChangedEventHandler PropertyChanged;


        private void OnPropertyChanged(string propertyName)
        {
            PropertyChangedEventHandler Handler = PropertyChanged;
            if (Handler != null) Handler(this, new PropertyChangedEventArgs(propertyName));
        }

        #endregion


        #region IDisposable Members

        public void Dispose()
        {
            if (View != null)
                View.Model = this;
            View = null;
            this.Model = null;
            this.Service = null;
        }

        #endregion


        #region Error Handling

        public string Error
        {
            get { throw new NotImplementedException(); }
        }

        public string this[string columnName]
        {
            get
            {
                string result = null;

                P2MessageStack propertyMessageStack = this.Model.Validator.ValidateProperty(this.Model, columnName);
                if (propertyMessageStack != null && propertyMessageStack.Count > 0)
                {
                    foreach (P2TransactionMessage message in propertyMessageStack)
                    {
                        if (message.TransactionStatus != "green")
                        {
                            if (result == null)
                                result = message.MessageText;
                            else
                                result += "\n" + message.MessageText;
                        }
                    }
                }
                return result;
            }
        }

        #endregion


    }
}
